/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package autobazarparser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

/**
 *
 * @author Ahmad Samir
 */
public class CarParser implements Parser {

    private DataSource carData;
    private PatternSource carPattern;
    private Document doc;
    private ArrayList<String> result;
    private ArrayList<String> multyPageResult;

    public CarParser() {
    }

    @Override
    public List<String> parse(PatternSource ps, DataSource ds) {

        this.carData = ds;
        this.carPattern = ps;

        result = new ArrayList<String>();
        doc = carData.getData();

        Elements nameList = doc.select(carPattern.getPatterns().get("Name").pattern());
        Elements infoList = doc.select(carPattern.getPatterns().get("Info").pattern());
        String[] infoString;

        for (int i = 0; i < nameList.size(); i++) {
            Elements carPrice = doc.select(carPattern.getPatterns().get("Price").pattern() + "[title*=" + nameList.get(i).text() + "]");
            result.add("Car: " + nameList.get(i).text() + ";");
            if (carPrice.isEmpty()) {
                result.add("Price: no Price;");
            } else {
                result.add("Price: " + carPrice.get(0).text() + ";");
            }
            infoString = infoList.get(i).html().replaceAll("<li>|(?<!цвет)\\s+", "").split("</li>");
            result.add("Engine: " + infoString[0].replace("&nbsp", ""));
            result.add("Mileage: " + infoString[1].replace("&nbsp", ""));
            result.add("Trans: " + infoString[2].replace("&nbsp", ""));
            result.add("Color: " + infoString[3].replace("&nbsp", "") + "\n");
        }

        return result;
    }

    @Override
    public List<String> parse(PatternSource ps, DataSource ds, int pages){


        multyPageResult = new ArrayList<String>();

        for (int i = 1; i < pages+1; i++) {
            try {
                ds = new CarData(ds.getSource() + "?page=" + i);
                System.out.println(ds.getSource());
            } catch (IOException ex) {
                Logger.getLogger(CarParser.class.getName()).log(Level.SEVERE, null, ex);
            }
            multyPageResult.addAll(parse(ps, ds));
        }
        return multyPageResult;
    }
}
